<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        size="small"
        placeholder="用户名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.nickname"
        size="small"
        placeholder="昵称"
        style="width: 200px;margin-left:2%"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="display:inline-block;margin-left:2%">县域：</p>
      <el-input
        v-model="listQuery.county"
        size="small"
        placeholder="管理员权限填写有效"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        :class-name="getSortClass('id')"
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="APP账户" width="250px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.nickname }}</span>
          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="地址" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="showReviewer"
        label="Reviewer"
        width="110px"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column label="县域" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.county }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="260"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <!-- <el-button
            v-if="row.status != 'published'"
            size="mini"
            type="success"
            @click="handleModifyStatus(row, 'published')"
          >
            Publish
          </el-button> -->
          <el-button
            type="danger"
            plain
            size="small"
            @click="handleLiaison(row)"
          >
            详细信息
          </el-button>
          <!-- <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleModifyStatus(row, 'deleted')"
          >
            Delete
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.start"
      :limit.sync="listQuery.lenth"
      @pagination="getList"
    />

    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="用户名">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="temp.nickname" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="temp.idcard" />
        </el-form-item>
        <el-form-item style="width:800px" label="地址">
          <v-distpicker
            :province="temp.province"
            :city="temp.city"
            :area="temp.county"
            @selected="select"
          />
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="temp.address" />
        </el-form-item>
        <el-form-item label="银行卡号">
          <el-input v-model="temp.bankcard" />
        </el-form-item>
        <el-form-item label="银行卡开户行">
          <el-input v-model="temp.openbank" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="outerVisible"
      append-to-body
      title="详情信息"
      width="60%"
    >
      <el-form
        :model="liaUserList"
        label-position="left"
        style="margin-left:50px;"
      >
        <el-form-item
          label-width="60px"
          style="float:left; width:33%"
          label="姓名:"
        >
          <span>{{ liaUserList.nickname }}</span>
        </el-form-item>
        <el-form-item
          label="性别："
          label-width="80px"
          style="float:left;width:33%"
        >
          <span>{{ liaUserList.sex == 1 ? "男" : "女" }}</span>
        </el-form-item>
        <el-form-item
          label-width="100px"
          style="float:left;width:33%"
          label="身份证号："
        >
          <span>{{ liaUserList.idcard }}</span>
        </el-form-item>
        <el-form-item
          label-width="60px"
          style="float:left;width:33%"
          label="地址："
        >
          <span>{{ liaUserList.address }}</span>
        </el-form-item>
        <el-form-item
          label-width="120px"
          style="float:left;width:33%"
          label="银行卡号："
        >
          <span>{{ liaUserList.bankcard }}</span>
        </el-form-item>
        <el-form-item
          label-width="120px"
          style="width:33%;float:left;"
          label="银行卡开户行："
        >
          <span>{{ liaUserList.openbank }}</span>
        </el-form-item>
      </el-form>
      <span
        style="display:inline-block; width:100%; height:1px; background:#E5E5E5;"
      />
      <div class="filter-container" style="margin-top:2%;" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="outerVisible = false">返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchXzxlList } from '@/api/article'// 异步请求 delLly
import { updateLiaison, createXzxl, llydetails, llydetailsList } from '@/api/appUser'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件

const calendarTypeOptions = [
  { key: 0, display_name: '无效' },
  { key: 1, display_name: '正常' },
  { key: 2, display_name: '锁定' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        start: 1,
        length: 10,
        username: '',
        nickname: '',
        county:'',
        sort: '+id'
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        province: '',
        city: '',
        county: '',
        approle: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      liaUserName: '',
      liaUserList: {},
      liaUser: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleLiaison(row) {
      this.outerVisible = true
      this.liaUserName = row.username
      llydetails(this.liaUserName).then(res => {
        this.liaUserList = res.data
      })
      llydetailsList(this.liaUserName).then(res => {
        this.liaUser = res.data
      })
    },
    select: function(data) {
      this.temp.provinceCode = data.province.code
      this.temp.cityCode = data.city.code
      this.temp.countyCode = data.area.code
      this.temp.province = data.province.value
      this.temp.city = data.city.value
      this.temp.county = data.area.value
    },
    getList() {
      this.listLoading = true
      var params = {
        pageConvert: true,
        start: this.listQuery.start,
        length: this.listQuery.length,
        username: this.listQuery.username,
        nickname: this.listQuery.nickname,
        county:this.listQuery.county
      }
      fetchXzxlList(params).then(response => {
        this.list = response.data
        console.log(this.list)
        this.total = response.recordsTotal
        console.log(this.total)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.approle = '3'
          createXzxl(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
      this.getList()
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateLiaison(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
      this.getList()
    },
    handleDelete(row) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
